const state = {
  themeColor: localStorage.getItem("theme-color") || "#409EFF",
  darkMode: localStorage.getItem("dark-mode") === "true",
  // 其他主题相关的状态
  fontSize: localStorage.getItem("font-size") || "medium",
  menuTheme: localStorage.getItem("menu-theme") || "dark",
};

const mutations = {
  SET_THEME_COLOR(state, color) {
    state.themeColor = color;
    localStorage.setItem("theme-color", color);
    document.documentElement.style.setProperty("--theme-color", color);
    // 设置衍生色
    const lightColor = color + "1A"; // 10% 透明度
    const darkColor = color;
    document.documentElement.style.setProperty(
      "--theme-color-light",
      lightColor
    );
    document.documentElement.style.setProperty("--theme-color-dark", darkColor);
  },
  SET_DARK_MODE(state, isDark) {
    state.darkMode = isDark;
    localStorage.setItem("dark-mode", isDark);
    document.documentElement.classList.toggle("dark-theme", isDark);
    // 更新背景色和文字颜色
    if (isDark) {
      document.body.style.backgroundColor = "#141414";
      document.body.style.color = "#ffffff";
    } else {
      document.body.style.backgroundColor = "#f0f2f5";
      document.body.style.color = "#303133";
    }
  },
  SET_FONT_SIZE(state, size) {
    state.fontSize = size;
    localStorage.setItem("font-size", size);
    document.documentElement.setAttribute("data-font-size", size);
  },
  SET_MENU_THEME(state, theme) {
    state.menuTheme = theme;
    localStorage.setItem("menu-theme", theme);
    document.documentElement.setAttribute("data-menu-theme", theme);
  },
};

const actions = {
  setThemeColor({ commit }, color) {
    commit("SET_THEME_COLOR", color);
  },
  setDarkMode({ commit }, isDark) {
    commit("SET_DARK_MODE", isDark);
  },
  setFontSize({ commit }, size) {
    commit("SET_FONT_SIZE", size);
  },
  setMenuTheme({ commit }, theme) {
    commit("SET_MENU_THEME", theme);
  },
  initTheme({ commit }) {
    // 初始化主题设置
    const color = localStorage.getItem("theme-color");
    if (color) commit("SET_THEME_COLOR", color);

    const darkMode = localStorage.getItem("dark-mode") === "true";
    commit("SET_DARK_MODE", darkMode);

    const fontSize = localStorage.getItem("font-size");
    if (fontSize) commit("SET_FONT_SIZE", fontSize);

    const menuTheme = localStorage.getItem("menu-theme");
    if (menuTheme) commit("SET_MENU_THEME", menuTheme);
  },
};

const getters = {
  themeColor: (state) => state.themeColor,
  isDarkMode: (state) => state.darkMode,
  fontSize: (state) => state.fontSize,
  menuTheme: (state) => state.menuTheme,
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
